package cryptology1

import (
	"os"
	"encoding/pem"
	"crypto/x509"
	"crypto/rsa"
	"crypto/rand"
)

/**
公钥加密
plainText是需要hash的原文件，fileName是密钥文件的路径
 */
func RSApublicEncrypt(plainText []byte,fileName string){
	//1.取出公钥
	file, _ := os.Open(fileName)
	fileInfo, _ := file.Stat()
	//2.创建缓冲区保存公钥
	bytes := make([]byte, fileInfo.Size())
	//3.读取公钥
	file.Read(bytes)
	//4.PEM 实质上是 Base64 编码的二进制内容，再加上开始和结束行
	block, _ := pem.Decode(bytes)
	pemBytes := block.Bytes
	//5.x509证书，ParsePKIXPublicKey解析一个DER编码的公钥。这些公钥一般在以"BEGIN PUBLIC KEY"出现的PEM块中
	publicKey, _ := x509.ParsePKIXPublicKey(pemBytes)
	pubKey := publicKey.(*rsa.PublicKey)
	//6.公钥加密
	rsa.EncryptPKCS1v15(rand.Reader, pubKey, plainText)

}
/**
私钥解密
 */
func RSAprivateDecrypt(plainText []byte,fileName string){
	//1.取出私钥
	file, _ := os.Open(fileName)
	fileInfo, _ := file.Stat()
	//2.创建缓冲区保存私钥
	bytes := make([]byte, fileInfo.Size())
	//3.读取私钥
	file.Read(bytes)
	//4.PEM 实质上是 Base64 编码的二进制内容，再加上开始和结束行
	block, _ := pem.Decode(bytes)
	pemBytes := block.Bytes
	//5.x509证书，ParsePKIXPublicKey解析一个DER编码的公钥。这些公钥一般在以"BEGIN PUBLIC KEY"出现的PEM块中
	privateKey, _ := x509.ParsePKCS1PrivateKey(pemBytes)
	//6.公钥加密
	rsa.DecryptPKCS1v15(rand.Reader, privateKey, plainText)
}